package com.wgh.product.service.impl;

import com.wgh.product.entity.shop.Product;
import com.wgh.common.vo.PageResult;
import com.wgh.common.vo.Result;
import com.wgh.product.mapper.ProductMapper;
import com.wgh.product.service.ProductService;
// import com.wgh.product.client.SearchServiceClient;
// import com.wgh.product.util.ProductDocConverter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品Service实现类
 * 
 * @author AI Shop
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    // 暂时注释掉搜索相关服务，后续会有客户端模块提供

    @Override
    public PageResult<Product> getProductPage(Map<String, Object> params, Integer pageNum, Integer pageSize) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0);
        
        // 构建查询条件
        if (params != null) {
            if (params.containsKey("status")) {
                queryWrapper.eq("status", params.get("status"));
            }
            if (params.containsKey("categoryId")) {
                queryWrapper.eq("category_id", params.get("categoryId"));
            }
            if (params.containsKey("brandId")) {
                queryWrapper.eq("brand_id", params.get("brandId"));
            }
            if (params.containsKey("keyword")) {
                queryWrapper.like("name", params.get("keyword"))
                           .or().like("description", params.get("keyword"));
            }
        }
        
        // 查询总数
        long total = baseMapper.selectCount(queryWrapper);
        
        // 查询列表
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("queryWrapper", queryWrapper);
        queryParams.put("pageNum", pageNum);
        queryParams.put("pageSize", pageSize);
        List<Product> productList = baseMapper.selectProductPage(queryParams);
        
        return new PageResult<>(pageNum, pageSize, total, productList);
    }

    @Override
    public Product getProductDetail(Long id) {
        return baseMapper.selectProductDetailById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addProduct(Product product) {
        return this.save(product);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateProduct(Product product) {
        return this.updateById(product);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateStatusBatch(List<Long> ids, Integer status) {
        return baseMapper.updateStatusBatch(ids, status) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updatePriceBatch(List<Long> ids, Double price) {
        return baseMapper.updatePriceBatch(ids, java.math.BigDecimal.valueOf(price)) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateStockBatch(List<Long> ids, Integer stock) {
        return baseMapper.updateStockBatch(ids, stock) > 0;
    }

    @Override
    public PageResult<Product> searchProducts(String keyword, Integer pageNum, Integer pageSize) {
        // 使用MyBatis-Plus的分页查询
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0)
                   .like("name", keyword)
                   .or().like("description", keyword);
        
        long total = baseMapper.selectCount(queryWrapper);
        Integer start = (pageNum - 1) * pageSize;
        List<Product> productList = baseMapper.searchProducts(keyword);
        
        // 手动分页
        if (productList != null && productList.size() > start) {
            int end = Math.min(start + pageSize, productList.size());
            productList = productList.subList(start, end);
        } else {
            productList = java.util.Collections.emptyList();
        }
        
        return new PageResult<>(pageNum, pageSize, total, productList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateViewCount(Long id) {
        return baseMapper.updateViewCount(id, 1) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateFavoriteCount(Long id, Integer increment) {
        return baseMapper.updateCollectCount(id, increment) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateSaleCount(Long id, Integer increment) {
        return baseMapper.updateSaleCount(id, increment) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteProduct(Long id) {
        // 标记为删除
        Product product = new Product();
        product.setId(id);
        product.setDelFlag(1); // 1表示已删除
        return this.updateById(product);
    }

    @Override
    public int countByCategoryId(Long categoryId) {
        return baseMapper.countByCategoryId(categoryId);
    }

    @Override
    public int countByBrandId(Long brandId) {
        return baseMapper.countByBrandId(brandId);
    }
}